<template>
  <div class="table-basic">
    <el-card class="table-card" shadow="hover">
      <template #header>
        <div class="card-header">
          <span class="card-title">数据表格</span>
          <div class="header-actions">
            <el-input
              v-model="searchText"
              placeholder="搜索用户..."
              style="width: 200px; margin-right: 16px;"
              :prefix-icon="Search"
              clearable
              @input="handleSearch"
            />
            <el-button type="primary" @click="handleAdd">
              <el-icon><Plus /></el-icon>
              新增用户
            </el-button>
          </div>
        </div>
      </template>
      
      <div class="table-content">
        <el-table
          :data="filteredTableData"
          style="width: 100%"
          stripe
          highlight-current-row
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="55" />
          
          <el-table-column prop="id" label="ID" width="80" />
          
          <el-table-column prop="avatar" label="头像" width="80">
            <template #default="scope">
              <el-avatar :size="40" :src="scope.row.avatar" />
            </template>
          </el-table-column>
          
          <el-table-column prop="name" label="姓名" width="120" />
          
          <el-table-column prop="email" label="邮箱" width="200" />
          
          <el-table-column prop="role" label="角色" width="100">
            <template #default="scope">
              <el-tag :type="getRoleType(scope.row.role)">
                {{ scope.row.role }}
              </el-tag>
            </template>
          </el-table-column>
          
          <el-table-column prop="status" label="状态" width="100">
            <template #default="scope">
              <el-tag :type="scope.row.status === '活跃' ? 'success' : 'danger'">
                {{ scope.row.status }}
              </el-tag>
            </template>
          </el-table-column>
          
          <el-table-column prop="createTime" label="创建时间" width="160" />
          
          <el-table-column prop="lastLogin" label="最后登录" width="160" />
          
          <el-table-column label="操作" width="200" fixed="right">
            <template #default="scope">
              <el-button size="small" @click="handleView(scope.row)">
                查看
              </el-button>
              <el-button size="small" type="primary" @click="handleEdit(scope.row)">
                编辑
              </el-button>
              <el-button size="small" type="danger" @click="handleDelete(scope.row)">
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        
        <div class="table-footer">
          <div class="selection-info">
            <span v-if="selectedRows.length > 0">
              已选择 {{ selectedRows.length }} 项
              <el-button size="small" type="danger" @click="handleBatchDelete">
                批量删除
              </el-button>
            </span>
          </div>
          
          <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :page-sizes="[10, 20, 50, 100]"
            :total="totalItems"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </div>
    </el-card>
    
    <!-- 用户详情对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="500px"
      @close="resetDialog"
    >
      <div v-if="dialogMode === 'view'" class="user-detail">
        <div class="detail-item">
          <label>头像：</label>
          <el-avatar :size="60" :src="currentUser.avatar" />
        </div>
        <div class="detail-item">
          <label>姓名：</label>
          <span>{{ currentUser.name }}</span>
        </div>
        <div class="detail-item">
          <label>邮箱：</label>
          <span>{{ currentUser.email }}</span>
        </div>
        <div class="detail-item">
          <label>角色：</label>
          <el-tag :type="getRoleType(currentUser.role)">{{ currentUser.role }}</el-tag>
        </div>
        <div class="detail-item">
          <label>状态：</label>
          <el-tag :type="currentUser.status === '活跃' ? 'success' : 'danger'">
            {{ currentUser.status }}
          </el-tag>
        </div>
        <div class="detail-item">
          <label>创建时间：</label>
          <span>{{ currentUser.createTime }}</span>
        </div>
        <div class="detail-item">
          <label>最后登录：</label>
          <span>{{ currentUser.lastLogin }}</span>
        </div>
      </div>
      
      <el-form v-else ref="dialogFormRef" :model="currentUser" :rules="formRules" label-width="80px">
        <el-form-item label="姓名" prop="name">
          <el-input v-model="currentUser.name" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="currentUser.email" />
        </el-form-item>
        <el-form-item label="角色" prop="role">
          <el-select v-model="currentUser.role" style="width: 100%">
            <el-option label="管理员" value="管理员" />
            <el-option label="编辑者" value="编辑者" />
            <el-option label="用户" value="用户" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="currentUser.status" style="width: 100%">
            <el-option label="活跃" value="活跃" />
            <el-option label="禁用" value="禁用" />
          </el-select>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button v-if="dialogMode !== 'view'" type="primary" @click="handleSave">
            保存
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Plus } from '@element-plus/icons-vue'

export default {
  name: 'TableBasic',
  components: {
    Search,
    Plus
  },
  setup() {
    const searchText = ref('')
    const currentPage = ref(1)
    const pageSize = ref(10)
    const totalItems = ref(0)
    const selectedRows = ref([])
    const dialogVisible = ref(false)
    const dialogMode = ref('view') // view, add, edit
    const dialogTitle = ref('')
    const dialogFormRef = ref(null)
    
    const tableData = ref([
      {
        id: 1,
        name: '张小明',
        email: 'zhangxiaoming@example.com',
        role: '管理员',
        status: '活跃',
        createTime: '2024-01-15 10:30:00',
        lastLogin: '2024-01-20 14:25:00',
        avatar: 'https://images.unsplash.com/photo-1507003211169-0a1dd7228f2d?w=100&h=100&fit=crop&crop=face'
      },
      {
        id: 2,
        name: '李小红',
        email: 'lixiaohong@example.com',
        role: '编辑者',
        status: '活跃',
        createTime: '2024-01-16 09:15:00',
        lastLogin: '2024-01-20 11:45:00',
        avatar: 'https://images.unsplash.com/photo-1494790108755-2616b612b601?w=100&h=100&fit=crop&crop=face'
      },
      {
        id: 3,
        name: '王小华',
        email: 'wangxiaohua@example.com',
        role: '用户',
        status: '禁用',
        createTime: '2024-01-17 16:20:00',
        lastLogin: '2024-01-19 08:30:00',
        avatar: 'https://images.unsplash.com/photo-1500648767791-00dcc994a43e?w=100&h=100&fit=crop&crop=face'
      },
      {
        id: 4,
        name: '赵小丽',
        email: 'zhaoxiaoli@example.com',
        role: '用户',
        status: '活跃',
        createTime: '2024-01-18 13:45:00',
        lastLogin: '2024-01-20 16:10:00',
        avatar: 'https://images.unsplash.com/photo-1438761681033-6461ffad8d80?w=100&h=100&fit=crop&crop=face'
      },
      {
        id: 5,
        name: '孙小军',
        email: 'sunxiaojun@example.com',
        role: '编辑者',
        status: '活跃',
        createTime: '2024-01-19 11:30:00',
        lastLogin: '2024-01-20 12:20:00',
        avatar: 'https://images.unsplash.com/photo-1472099645785-5658abf4ff4e?w=100&h=100&fit=crop&crop=face'
      }
    ])
    
    const currentUser = reactive({
      id: null,
      name: '',
      email: '',
      role: '',
      status: '',
      createTime: '',
      lastLogin: '',
      avatar: ''
    })
    
    const formRules = reactive({
      name: [
        { required: true, message: '请输入姓名', trigger: 'blur' }
      ],
      email: [
        { required: true, message: '请输入邮箱', trigger: 'blur' },
        { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
      ],
      role: [
        { required: true, message: '请选择角色', trigger: 'change' }
      ],
      status: [
        { required: true, message: '请选择状态', trigger: 'change' }
      ]
    })
    
    const filteredTableData = computed(() => {
      if (!searchText.value) {
        return tableData.value
      }
      return tableData.value.filter(item =>
        item.name.toLowerCase().includes(searchText.value.toLowerCase()) ||
        item.email.toLowerCase().includes(searchText.value.toLowerCase())
      )
    })
    
    const getRoleType = (role) => {
      const types = {
        '管理员': 'danger',
        '编辑者': 'warning',
        '用户': 'info'
      }
      return types[role] || 'info'
    }
    
    const handleSearch = () => {
      currentPage.value = 1
    }
    
    const handleSelectionChange = (selection) => {
      selectedRows.value = selection
    }
    
    const handleAdd = () => {
      dialogMode.value = 'add'
      dialogTitle.value = '新增用户'
      resetCurrentUser()
      dialogVisible.value = true
    }
    
    const handleView = (row) => {
      dialogMode.value = 'view'
      dialogTitle.value = '用户详情'
      Object.assign(currentUser, row)
      dialogVisible.value = true
    }
    
    const handleEdit = (row) => {
      dialogMode.value = 'edit'
      dialogTitle.value = '编辑用户'
      Object.assign(currentUser, row)
      dialogVisible.value = true
    }
    
    const handleDelete = (row) => {
      ElMessageBox.confirm(
        `确定要删除用户 "${row.name}" 吗？`,
        '确认删除',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).then(() => {
        const index = tableData.value.findIndex(item => item.id === row.id)
        if (index > -1) {
          tableData.value.splice(index, 1)
          ElMessage.success('删除成功')
        }
      }).catch(() => {
        ElMessage.info('已取消删除')
      })
    }
    
    const handleBatchDelete = () => {
      ElMessageBox.confirm(
        `确定要删除选中的 ${selectedRows.value.length} 个用户吗？`,
        '确认批量删除',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).then(() => {
        const selectedIds = selectedRows.value.map(row => row.id)
        tableData.value = tableData.value.filter(item => !selectedIds.includes(item.id))
        selectedRows.value = []
        ElMessage.success('批量删除成功')
      }).catch(() => {
        ElMessage.info('已取消删除')
      })
    }
    
    const handleSave = () => {
      dialogFormRef.value.validate((valid) => {
        if (valid) {
          if (dialogMode.value === 'add') {
            currentUser.id = tableData.value.length + 1
            currentUser.createTime = new Date().toLocaleString()
            currentUser.lastLogin = new Date().toLocaleString()
            currentUser.avatar = 'https://images.unsplash.com/photo-1507003211169-0a1dd7228f2d?w=100&h=100&fit=crop&crop=face'
            tableData.value.push({ ...currentUser })
            ElMessage.success('新增成功')
          } else {
            const index = tableData.value.findIndex(item => item.id === currentUser.id)
            if (index > -1) {
              Object.assign(tableData.value[index], currentUser)
              ElMessage.success('修改成功')
            }
          }
          dialogVisible.value = false
        }
      })
    }
    
    const resetCurrentUser = () => {
      Object.assign(currentUser, {
        id: null,
        name: '',
        email: '',
        role: '',
        status: '',
        createTime: '',
        lastLogin: '',
        avatar: ''
      })
    }
    
    const resetDialog = () => {
      if (dialogFormRef.value) {
        dialogFormRef.value.resetFields()
      }
      resetCurrentUser()
    }
    
    const handleSizeChange = (size) => {
      pageSize.value = size
      currentPage.value = 1
    }
    
    const handleCurrentChange = (page) => {
      currentPage.value = page
    }
    
    onMounted(() => {
      totalItems.value = tableData.value.length
    })
    
    return {
      searchText,
      currentPage,
      pageSize,
      totalItems,
      selectedRows,
      tableData,
      filteredTableData,
      dialogVisible,
      dialogMode,
      dialogTitle,
      dialogFormRef,
      currentUser,
      formRules,
      getRoleType,
      handleSearch,
      handleSelectionChange,
      handleAdd,
      handleView,
      handleEdit,
      handleDelete,
      handleBatchDelete,
      handleSave,
      resetDialog,
      handleSizeChange,
      handleCurrentChange
    }
  }
}
</script>

<style scoped>
.table-basic {
  padding: 20px;
}

.table-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-title {
  font-size: 18px;
  font-weight: 500;
  color: #333;
}

.header-actions {
  display: flex;
  align-items: center;
}

.table-content {
  padding: 20px 0;
}

.table-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 20px;
}

.selection-info {
  color: #666;
}

.user-detail {
  padding: 20px 0;
}

.detail-item {
  display: flex;
  align-items: center;
  margin-bottom: 16px;
}

.detail-item label {
  font-weight: 500;
  color: #333;
  width: 80px;
  margin-right: 12px;
}

@media (max-width: 768px) {
  .table-basic {
    padding: 10px;
  }
  
  .card-header {
    flex-direction: column;
    gap: 16px;
    align-items: stretch;
  }
  
  .header-actions {
    flex-direction: column;
    gap: 12px;
  }
  
  .table-footer {
    flex-direction: column;
    gap: 16px;
    align-items: stretch;
  }
}
</style>
